<?php
/*
* filename: template.php

* modifier: iwind , faps

* date: 2006-11-13 16:29

* description: Template class

*/

class Template
{
	var $classname 	= "Template";
	var $debug 		= false;
	var $file  		= array();
	var $root   	= "";
	var $varkeys 	= array();
	var $varvals 	= array();
    var $pairs;

	var $unknowns 	= "remove";

	function Template($root = "..", $unknowns = "remove")
	{
		$this->setRoot($root);
		$this->unknowns = $unknowns;
	}

	function setRoot($root)
	{
		if (!is_dir($root))
		{
			$this->errMsg("setRoot: {$root} 目录不存在");
			return false;
		}
		$this->root = $root;
		return true;
	}

	function setFile($handle, $filename = "")
	{
		if (!is_array($handle))
		{
			if ($filename == "")
			{
				$this->errMsg("setFile: 句柄 {$handle} 所指定的文件({$filename})内容为空");
				return false;
			}
			$this->file[$handle] = $this->filename($filename);
		}
		else
		{
			reset($handle);
			while(list($h, $f) = each($handle))
			{
				$this->file[$h] = $this->filename($f);
			}
		}
	}

	function setBlock($parent, $handle, $name = "")
	{
		if (!$this->loadfile($parent))
		{
			$this->errMsg("setBlock: 无法加载句柄 {$parent}");
			return false;
		}
		if ($name == "")
		$name = $handle;
		$str = $this->getVar($parent);
		$reg = "/<!--\s*BEGIN[ ]+$handle\s*-->(.*)\s*<!--\s*END[ ]+$handle\s*-->/ism";
		preg_match_all($reg, $str, $m);
		$str = preg_replace($reg, "{" . "$name}", $str);
		@$this->setVar($handle, $m[1][0]);
		$this->setVar($parent, $str);
	}

	function setVar($varname, $value = "")
	{
		if (!is_array($varname))
		{
			if (!empty($varname))
			if ($this->debug) print "setVar: *{$varname}* => *{$value}*<br>\n";
			$this->varkeys[$varname] = "/".$this->varname($varname)."/";
			$this->varvals[$varname] = $value;
            $this->pairs["{" . $varname . "}"] = $value;
		}
		else
		{
			reset($varname);
			while(list($k, $v) = each($varname))
			{
				if (!empty($k))
				if ($this->debug) print "array: *{$k}* => *{$v}*<br>\n";
				$this->varkeys[$k] = "/".$this->varname($k)."/";
				$this->varvals[$k] = $v;
                $this->pairs["{" . $k . "}"] = $v;
			}
		}
	}

	function subst($handle)
	{
		if (!$this->loadfile($handle))
		{
			$this->errMsg("subst: 无法加载句柄 {$handle}");
			return false;
		}
		$str = $this->getVar($handle);
		//$str = preg_replace($this->varkeys, $this->varvals, $str);
        $str = strtr($str, $this->pairs);
		return $str;
	}

	function parse($target, $handle, $append = false)
	{
		if (!is_array($handle))
		{
			$str = $this->subst($handle);
			if ($append)
			{
				$this->setVar($target, $this->getVar($target) . $str);
			}
			else
			{
				$this->setVar($target, $str);
			}
		}
		else
		{
			reset($handle);
			while(list($i, $h) = each($handle))
			{
				$str = $this->subst($h);
				$this->setVar($target, $str);
			}
		}
		return $str;
	}

	function getVar($varname)
	{
		if (!is_array($varname))
		{
			return @$this->varvals[$varname];
		}
		else
		{
			reset($varname);
			while(list($k, $v) = each($varname))
			{
				$result[$k] = $this->varvals[$k];
			}
			return $result;
		}
	}

	function finish($str)
	{
		switch ($this->unknowns)
		{
			case "keep":
				break;
			case "remove":
				$str = preg_replace('/{[a-z]+[\w\_\.\-]+}/i', "", $str);
				break;
			case "comment":
				$str = preg_replace('/{([a-z]+[\w\_\.\-]+)}/', "<!-- Template: 模板变量 \\1 未定义 -->", $str);
				break;
		}
		return $str;
	}

	function get($varname)
	{
		return $this->finish($this->getVar($varname));
	}

	function filename($filename)
	{
		if (substr($filename, 0, 1) != "/")
		{
			$filename = $this->root."/".$filename;
		}
		if (!file_exists($filename))
			$this->errMsg("filename: {$filename} 文件不存在");
		return $filename;
	}

	function varname($varname)
	{
		return preg_quote("{".$varname."}");
	}

	function loadfile($handle)
	{
		if (isset($this->varkeys[$handle]) and !empty($this->varvals[$handle]))
			return true;

		if (!isset($this->file[$handle]))
		{
			$this->errMsg("loadfile: {$handle} 无效句柄");
			return false;
		}
		$filename = $this->file[$handle];

		$str = @implode("", @file($filename));
		if (empty($str))
		{
			$this->errMsg("loadfile: 句柄 {$handle} 所指定的文件 {$filename} 文件不存在或内容为空");
			return false;
		}
		//add 2004-2-4
		$str=str_replace("%7B","{",$str);
		$str=str_replace("%7D","}",$str);
		//
		$this->setVar($handle, $str);
		return true;
	}

	function save($fn,$varname)
	{
		$save_out = "";
		if(is_array($varname))
		{
			foreach($varname as $vvn)
			{
				$save_out .= $this->get($vvn."s");
			}
		}
		else
		{
			$this->parse($varname."s",$varname);
			$save_out = $this->get($varname."s");
		}
		@fwrite(fopen($fn,"w+"), $save_out);
	}

	function renew()
	{
		$this->varkeys = array();
		$this->varvals = array();
		$this->file = array();
	}

	function p($varname)
	{
		$this->parse($varname."s",$varname);
		print $this->get($varname."s");
	}

	function pprint($varname)
	{
		print $this->get($varname);
	}

	function errMsg($msg)
	{
		global $CFG;
		if(isset($CFG["err"]))
		{
			switch($CFG["err"]["mode"])
			{
				case 1:
					header("Location: {$CFG['err']['page']}");
					die();
					break;

				case 2:
					return;
					break;
			}
		}

		die("<style>body{font-size:12px;}</style><br/><font color=red>template class 错误:</font><hr size=1 color=#0099ff>来源: {$_SERVER['REQUEST_URI']}<br/>信息: {$msg}");
	}
}
?>